package com.oron3.locker;

import android.app.AlertDialog;
import android.app.ListActivity;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ListView;
import android.widget.TextView;

import com.ofek.applicationbase.adapter.BaseAdapter;
import com.oron3.lock.R;
import com.oron3.locker.SecretEdit.State;
import com.oron3.locker.ToolController.ToolAdapter;

public class SecretFormActivity extends ListActivity {
	public final static String KEY_INTENT_EXTRA_SECRET_TO_EDIT = "com.oron3.Lock.KEY_INTENT_EXTRA_SECRET_TO_EDIT";
	private static final String KEY_SECRET_STATE = "com.oron3.Lock.KEY_SECRET_STATE";
	private static final String KEY_CHANGED = "com.oron3.Lock.KEY_CHANGED";
	private AES aes;
	private ToolController toolController;
	private LockDatabase lockDatabase;
	private TextView titleInTool;
	private SecretAdapter adapter;
	private SecretHolder secretHolder;
	private boolean edit;
	private boolean changed;
	private Secret editingSecret;

	public class SecretAdapter extends BaseAdapter {
		/**
		 *
		 */
		public SecretAdapter() {
			super(getApplicationContext(), R.layout.list_item_secret);

		}

		/*
		 * (non-Javadoc)
		 * 
		 * @see android.widget.Adapter#getCount()
		 */
		@Override
		public int getCount() {
			return secretHolder.size();
		}

		/*
		 * (non-Javadoc)
		 * 
		 * @see android.widget.Adapter#getItem(int)
		 */
		@Override
		public Object getItem(final int position) {
			return secretHolder.get(position); // secrets
		}

		/*
		 * (non-Javadoc)
		 * 
		 * @see android.widget.Adapter#getItemId(int)
		 */
		@Override
		public long getItemId(final int position) {
			return secretHolder.get(position).sid_id;
		}

		/*
		 * (non-Javadoc)
		 * 
		 * @see com.ofek.applicationbase.adapter.BaseAdapter#adjustView(int,
		 * android.view.View)
		 */
		@Override
		public void adjustView(final int position, final View convertView) {
			final TextView title = (TextView) convertView.findViewById(R.id.title);
			final TextView seceret = (TextView) convertView.findViewById(R.id.secret);
			final Secret actualSecret = secretHolder.get(position);
			title.setText(actualSecret.secretTitle);
			seceret.setText(actualSecret.secret);
			final View delete = convertView.findViewById(R.id.delete);
			delete.setVisibility(toolController.getEditState() ? View.VISIBLE : View.INVISIBLE);
			delete.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(final View v) {
					secretHolder.remove(actualSecret);
					notifyDataSetChanged();
					changed = true;
				}
			});
		}

	}

	private final Runnable onConfirm = new Runnable() {

		@Override
		public void run() {
			if (secretEditor.getState() == State.ADD)
				secretHolder.add(new Secret(secretEditor.getTitle(), secretEditor.getSecret()));
			else if (secretEditor.getState() == State.EDIT) {
				editingSecret.secret = secretEditor.getSecret();
				editingSecret.secretTitle = secretEditor.getTitle();
			}
			changed = true;
			toolController.setAddState(false);
			secretEditor.setState(State.INVISIBLE);
			adapter.notifyDataSetChanged();
		}
	};
	private SecretEdit secretEditor;

	@Override
	protected void onCreate(final Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setContentView(R.layout.activity_secret_form);
		if (!getIntent().hasExtra(LockActivity.KEY_INTENT_EXTRA_UC)) {
			startActivity(new Intent(this, LoginActivity.class));
			finish();
			return;
		}
		toolController = new ToolController((ViewGroup) findViewById(R.id.tool));
		toolController.setEditState(false);
		toolController.setTitleVisibility(true);
		lockDatabase = LockDatabase.getInstance(getIntent().getStringExtra(LockActivity.KEY_INTENT_EXTRA_UC));
		toolController.setAddAsToggle(true);
		toolController.setTitleVisibility(true);
		secretEditor = (SecretEdit) findViewById(R.id.secretEditor);
		secretEditor.setOnConfirm(onConfirm);
		final SecretID serializableExtra = (SecretID) getIntent().getSerializableExtra(KEY_INTENT_EXTRA_SECRET_TO_EDIT);
		if (serializableExtra != null) {
			setTitle(R.string.edit);
			edit = true;
			if (savedInstanceState != null && savedInstanceState.containsKey(KEY_SECRET_STATE)) {
				secretHolder = (SecretHolder) savedInstanceState.getSerializable(KEY_SECRET_STATE);
				changed = savedInstanceState.getBoolean(KEY_CHANGED);
			} else
				secretHolder = lockDatabase.getHolder(serializableExtra);
			toolController.setTitle(secretHolder.id.title);
		} else {
			setTitle(R.string.add);
			edit = false;
			if (savedInstanceState != null && savedInstanceState.containsKey(KEY_SECRET_STATE)) {
				secretHolder = (SecretHolder) savedInstanceState.getSerializable(KEY_SECRET_STATE);
				changed = savedInstanceState.getBoolean(KEY_CHANGED);
			} else
				secretHolder = new SecretHolder();
			toolController.setEditState(true);
			toolController.setAddState(true);
		}
		adapter = new SecretAdapter();
		toolController.registerToolListener(new ToolAdapter() {

			/*
			 * (non-Javadoc)
			 * 
			 * @see
			 * com.oron3.locker.ToolController.ToolAdapter#onAddChecked(boolean)
			 */
			@Override
			public void onAddChecked(final boolean b) {
				if (b)
					secretEditor.setState(SecretEdit.State.ADD);
				else
					secretEditor.setState(State.INVISIBLE);
			}

			@Override
			public void onEditChecked(boolean b) {
				// TODO Auto-generated method stub
				super.onEditChecked(b);
				adapter.notifyDataSetInvalidated();
			}

			/*
			 * (non-Javadoc)
			 * 
			 * @see
			 * com.oron3.locker.ToolController.ToolAdapter#onTitleEdited(java
			 * .lang.String)
			 */
			@Override
			public void onTitleEdited(final String newer) {
				secretHolder.id.title = newer;
				changed = true;
			}

			@Override
			public void onSave() {
				super.onSave();
				save();
			}
		}, true);

		setListAdapter(adapter);
	}

	protected void save() {
		if (edit)
			lockDatabase.replace(secretHolder);
		else
			lockDatabase.add(secretHolder);
		finish();
	}

	@Override
	protected void onResume() {
		super.onResume();

	}

	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();

	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see android.app.ListActivity#onDestroy()
	 */
	@Override
	protected void onDestroy() {
		super.onDestroy();
		lockDatabase.release();
	}

	@Override
	protected void onListItemClick(final ListView l, final View v, final int position, final long id) {
		toolController.setAddState(false);
		secretEditor.setState(SecretEdit.State.EDIT);
		editingSecret = secretHolder.get(position);
		secretEditor.setSecret(editingSecret);

	}

	@Override
	protected void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
		outState.putSerializable(KEY_SECRET_STATE, secretHolder);
		outState.putBoolean(KEY_CHANGED, changed);
	}

	@Override
	public void onBackPressed() {

		if (!changed)
			finish();
		else {
			final DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					switch (which) {
					case DialogInterface.BUTTON_POSITIVE:
						save();
						break;

					case DialogInterface.BUTTON_NEGATIVE:
						finish();
						break;
					}
				}
			};
			final AlertDialog.Builder builder = new AlertDialog.Builder(this);
			builder.setMessage("Save changes?").setPositiveButton("Yes", dialogClickListener).setNegativeButton("No", dialogClickListener).show();
		}
	}

}
